import httpx
from typing import List, Dict, Any, Optional
from loguru import logger
from app.core.config import settings
from app.schemas.deepseek import Message, PromptRequest, ChatRequest, PromptResponse, ChatResponse

class DeepSeekService:
    """DeepSeek API服务"""
    def __init__(self):
        self.api_key = settings.DEEPSEEK_API_KEY
        self.api_base = settings.DEEPSEEK_API_BASE
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    async def generate_prompt(self, request: PromptRequest) -> Dict:
        """
        生成提示词
        """
        try:
            # 构建系统提示词
            system_prompt = (
                "你是一个专业的提示词工程师，擅长将用户的中文描述转换为高质量的英文提示词。"
                "请按照以下要求工作：\n"
                "1. 仔细理解用户的中文描述\n"
                "2. 提取关键信息和要求\n"
                "3. 转换为清晰、准确的英文提示词\n"
                "4. 使用合适的关键词和修饰语\n"
                "5. 保持提示词的简洁性和可执行性"
            )
            if request.prompt_type == "master":
                system_prompt += (
                    "\n6. 使用更专业的术语和表达\n"
                    "7. 添加更多细节和约束条件\n"
                    "8. 确保生成的内容具有艺术性和创造性"
                )

            messages = [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": request.input_text}
            ]

            async with httpx.AsyncClient() as client:
                response = await client.post(
                    f"{self.api_base}/chat/completions",
                    headers=self.headers,
                    json={
                        "messages": messages,
                        "temperature": request.temperature,
                        "max_tokens": request.max_tokens
                    }
                )
                response.raise_for_status()
                result = response.json()
                
                return {
                    "code": 200,
                    "message": "success",
                    "data": {
                        "output_text": result["choices"][0]["message"]["content"],
                        "parameters": {
                            "temperature": request.temperature,
                            "max_tokens": request.max_tokens
                        }
                    }
                }
        except Exception as e:
            logger.error(f"生成提示词失败: {str(e)}")
            raise

    async def chat(self, request: ChatRequest) -> Dict:
        """
        对话
        """
        try:
            messages = [
                {"role": "user", "content": request.input_text}
            ]

            async with httpx.AsyncClient() as client:
                response = await client.post(
                    f"{self.api_base}/chat/completions",
                    headers=self.headers,
                    json={
                        "messages": messages,
                        "temperature": request.temperature,
                        "max_tokens": request.max_tokens,
                        "top_p": request.top_p,
                        "frequency_penalty": request.frequency_penalty,
                        "presence_penalty": request.presence_penalty
                    }
                )
                response.raise_for_status()
                result = response.json()
                
                return {
                    "code": 200,
                    "message": "success",
                    "data": {
                        "output_text": result["choices"][0]["message"]["content"],
                        "parameters": {
                            "temperature": request.temperature,
                            "max_tokens": request.max_tokens
                        }
                    }
                }
        except Exception as e:
            logger.error(f"对话失败: {str(e)}")
            raise 